﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kokomo.PeInspector.ObjectGraphs
{
	class BackreferenceTemplate<TNode> : ObjectTemplate<TNode>
	{
		public BackreferenceTemplate(
			IEnumerable<MemberTemplate> memberTemplates,
			IEqualityComparer<TNode> comparer
			)
			: base(memberTemplates)
		{
			if (comparer == null)
				comparer = EqualityComparer<TNode>.Default;
			this.Comparer = comparer;
		}

		public IEqualityComparer<TNode> Comparer { get; private set; }

		public override bool Inspect(object value)
		{
			if ((this.CapturedValue != null))
			{
				if (!(value is TNode))
					return false;

				TNode typedValue = (TNode)value;
				return this.Comparer.Equals(this.CapturedValue, typedValue);
			}

			bool matches = base.Inspect(value);
			if (matches)
			{
				this.CapturedValue = (TNode)value;
			}

			return matches;
		}
	}
}
